/**
 * 
 */
package cn.jhz.filesharingsystem.web;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.jhz.filesharingsystem.service.PermissionService;
import cn.jhz.filesharingsystem.util.AuthUtil;
import cn.jhz.filesharingsystem.util.UploadPropertiesUtil;



/**
 * @author asus
 *
 */
public class InitWebServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	/*
	 * init:初始化(Spring的IOC容器的引用初始化到此类的一个静态方法) 
	 * 			   (初始化权限)
	 */
	static private ApplicationContext applicationContext;

	static public ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void init() throws ServletException {
		
		try {
			//(Spring的IOC容器的引用初始化到此类的一个静态方法)
			ServletContext context = getServletContext();
			
			//注入配置
			injectionProperties();
			UploadPropertiesUtil.getInstance().addProperty("savePath", context.getRealPath(UploadPropertiesUtil.getInstance().getProperty("savePath")));

			applicationContext = WebApplicationContextUtils.getWebApplicationContext(context);
			//(初始化权限)
			//权限控制的包
			String packageName ="cn.jhz.filesharingsystem.controller";
			String packageNamePath = packageName.replace(".", "/");
			//获取包在服务器磁盘的绝对路径
			String packageNameRealPath = this.getClass().getClassLoader().getResource(packageNamePath).getPath();
			
			File file = new File(URLDecoder.decode(packageNameRealPath,"UTF-8"));  //file是controller在磁盘上的文件
			//遍历文件夹文件
			String[] classFileNames = file.list(new FilenameFilter() {
				
				@Override
				public boolean accept(File dir, String name) {
					if(name.endsWith(".class")){
						return true;
					}
					return false;
				}
			});
			
			List<String> resources = new ArrayList<>();
			
			for(String classFileName: classFileNames) {
				//.class去掉
				classFileName = classFileName.substring(0, classFileName.indexOf(".class"));
				//包全名
				String calssAllpackageName = packageName+'.'+classFileName;
				//拿到包全名
				@SuppressWarnings("rawtypes")
				Class clazz = Class.forName(calssAllpackageName);
				//拿到这些controller的对象,获取到他们的注解
				if(!clazz.isAnnotationPresent(AuthClass.class)) continue;
				//剩下的类,都是有@AuthClass的类,这些类都需要权限控制
				//获取这些类的方法(包含private)
				Method[] methods = clazz.getDeclaredMethods();
				for (Method method : methods) {
					if(!method.isAnnotationPresent(AuthMethod.class)) continue;
					//过滤没有@Authmethod的方法
					//1:cn.jhz.filesharingsystem.controller.method作为resource
//					String resourceC = calssAllpackageName+'.'+method.getName();
					//2:"视图"作为resource
//					RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
					
					resources.add(AuthUtil.getURL(method));
			
				}
			}
			resources.add("");
			PermissionService permissionService = (PermissionService) applicationContext.getBean("permissionService");
			permissionService.initPermissions(resources);
			context.setAttribute("allPermRes", resources);    //系统中所有需要权限控制的url
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private void injectionProperties() {
//      web服务器启动的时间执行
	 	InputStream in = getClass().getClassLoader().getResourceAsStream("uploadfile.properties");
	
	 	Properties properties = new Properties();
	 	try {
				properties.load(in);
				for (Object obj : properties.keySet()) {
					String key = (String)obj;
					String value = properties.getProperty(key);
					UploadPropertiesUtil.getInstance().addProperty(key, value);
				}
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
}
